﻿<!DOCTYPE html>
<html ng-app="directiveApp">
<head>
    <title></title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <script src="scripts/angular.min.js"></script>
    <script>
        angular.module("directiveApp", [])
            .directive("unorderedList", function () {
                return function (scope, element, attrs) {
                    var data = scope[attrs["unorderedList"]];
                    var propertyName = attrs["listProperty"];   // 从调用者处获得要依赖的属性
                    if (angular.isArray(data)) {
                        var listElem = angular.element("<ul>");
                        element.append(listElem);
                        for (var i = 0; i < data.length; i++) {
                            /*
                                如果直接使用data[i][propertyName]，将无法应对下列情况：
                                <div unordered-list="products" list-property="price | currency"></div>
                                此时应使用scope.$eval，该方法将能够生成angular所能识别的语句
                            */
                            // listElem.append(angular.element('<li>').text(data[i][propertyName]));
                            listElem.append(angular.element('<li>').text(
                                scope.$eval(propertyName, data[i])
                                ));
                        }
                    }
                }
            })
            .controller("defaultCtrl", function ($scope) {
                $scope.products = [
                    { name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
                    { name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
                    { name: "Pears", category: "Fruit", price: 2.02, expiry: 6 }
                ];
            });
    </script>
</head>
<body ng-controller="defaultCtrl">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3>Products</h3>
        </div>
        <div class="panel-body">
            <div unordered-list="products" list-property="name"></div>
            <div unordered-list="products" list-property="price | currency"></div>
        </div>
    </div>
</body>
</html>
